﻿using Futajma.MigrationStudio.DataDefinition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Futajma.MigrationStudio.LiveLinkImporter.TreeActions
{
    internal class TreeData
    {
        Dictionary<string, TreeNode> _sourceTreeNodes;
        Dictionary<string, TreeNode> _targetTreeNodes;

        public TreeData()
        {
            _sourceTreeNodes = new Dictionary<string, TreeNode>();
            _targetTreeNodes = new Dictionary<string, TreeNode>();
        }

        public void PopulateTrees(TreeView sourceTreeView, TreeView targetTreeView)
        {
            _sourceTreeNodes.Clear();
            _targetTreeNodes.Clear();

            foreach (TreeNode node in sourceTreeView.Nodes)
            {
                PopulateRecursive(node, _sourceTreeNodes);
            }

            foreach (TreeNode node in targetTreeView.Nodes)
            {
                PopulateRecursive(node, _targetTreeNodes);
            }
        }

        internal TreeNode GetSourceNode(string key)
        {
            if (_sourceTreeNodes.ContainsKey(key))
            {
                return _sourceTreeNodes[key];
            }
            else
            {
                return null;
            }
        }

        internal TreeNode GetTargetNode(string key)
        {
            if (_targetTreeNodes.ContainsKey(key))
            {
                return _targetTreeNodes[key];
            }
            else
            {
                return null;
            }
        }

        internal void AddSourceNode(TreeNode node)
        {
            var data = node.Tag as DataNode;

            if (!string.IsNullOrEmpty(data.SourceId) && !_sourceTreeNodes.ContainsKey(data.SourceId))
            {
                _sourceTreeNodes.Add(data.SourceId, node);
            }
        }

        private void PopulateRecursive(TreeNode node, Dictionary<string, TreeNode> treeNodes)
        {
            var data = node.Tag as DataNode;

            if (!string.IsNullOrEmpty(data.SourceId))
            {
                treeNodes.Add(data.SourceId, node);
            }
            foreach (TreeNode child in node.Nodes)
            {
                PopulateRecursive(child, treeNodes);
            }
        }



        static TreeNode FindNode(TreeNode node, string liveLinkId)
        {

            Data.DataNode data = node.Tag as Data.DataNode;

            if (data != null && data.SourceId == liveLinkId)
            {
                return node;
            }

            foreach (TreeNode child in node.Nodes)
            {
                var match = FindNode(child, liveLinkId);

                if (match != null)
                {
                    return match;
                }
            }

            return null;
        }
    }
}
